import 'package:flutter/cupertino.dart';
// import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim/routes/app_navigator.dart';
import 'package:openim_common/openim_common.dart';
import 'package:sprintf/sprintf.dart';

import 'login_logic.dart';

class LoginPage extends StatelessWidget {
  final logic = Get.find<LoginLogic>();

  LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Material(
      child: TouchCloseSoftKeyboard(
        isGradientBg: true,
        child: LayoutBuilder(
        builder: (context, constraints) 
          {
            return SingleChildScrollView(
              child: ConstrainedBox(
                constraints: BoxConstraints(
                  minHeight: constraints.maxHeight,
                ),
      
              child: Column(
                children: [
                  SizedBox(height: constraints.maxHeight * 0.25 - 32.h), // 减去Logo高度的一半来居中
                  ImageRes.loginLogo.toImage
                    ..width = 64.w
                    ..height = 64.h,
                  // StrRes.welcome.toText..style = Styles.ts_0089FF_17sp_semibold,
                  51.verticalSpace,
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 32.w),
                    child: Column(children: [
                      _buildInputView(),
                      // 1.verticalSpace,
                      Obx(() => Button(
                            text: StrRes.login,
                            enabled: logic.enabled.value,
                            enabledColor: Styles.c_FFB300,  // 添加这行：设置按钮颜色为淡黄色
                            onTap: logic.login,
                          )),
                    ]),
                  ),
                  100.verticalSpace,
                  // Obx(
                  //   () => Visibility(
                  //     visible: logic.loginType.value != LoginType.account,
                  //     child: RichText(
                  //       text: TextSpan(
                  //         text: StrRes.noAccountYet,
                  //         style: Styles.ts_8E9AB0_12sp,
                  //         children: [
                  //           TextSpan(
                  //             text: StrRes.registerNow,
                  //             style: Styles.ts_0089FF_12sp,
                  //             recognizer: TapGestureRecognizer()..onTap = _showRegisterBottomSheet,
                  //           )
                  //         ],
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  32.verticalSpace,
                  Padding(
                  padding: EdgeInsets.symmetric(horizontal: 32.w),
                  child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: _buildCircleButton(
                        icon: Icons.person_outline,
                        label: '其他方式登录',
                        onTap: () {
                          // 处理其他方式登录
                          _showOtherLoginMethods();
                        },
                      ),
                    ),
                    Expanded(
                      child: _buildCircleButton(
                        icon: Icons.add,
                        label: '注册',
                        onTap: _showRegisterBottomSheet,
                      ),
                    ),
                    Expanded(
                      child: _buildCircleButton(
                        icon: Icons.more_horiz,
                        label: '更多',
                        onTap: () {
                          // 处理更多选项
                          _showMoreOptions();
                        },
                      ),
                    ),
                  ],
                ),
                ),
                  // Obx(() => rlogic.versionInfo.value.toText..style = Styles.ts_0C1C33_14sp),
                ],
              ),
            ),
          );
          }
        )
      )
    );
  }
  Widget _buildInputView() {
      return Container(
      height: 180.h,
      width: 300.w,
      child:  Obx(() {
        final type = logic.loginType.value;
        debugPrint('loginType: $type');
        return type == LoginType.phone ? _buildInputView1(type) : _buildInputView2(type);
      }),
    );
  }

  Widget _buildInputView1(LoginType type) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Obx(() => InputBox.account(
          label: '',
          hintText: type.hintText,
          code: logic.areaCode.value,
          onAreaCode: type == LoginType.phone ? logic.openCountryCodePicker : null,
          controller: logic.phoneCtrl,
          focusNode: logic.accountFocus,
          keyBoardType: type == LoginType.phone ? TextInputType.phone : TextInputType.text,
        )),
        8.verticalSpace,
        Offstage(
          offstage: !logic.isPasswordLogin.value,
          child: InputBox.password(
            label: '',
            hintText: StrRes.plsEnterPassword,
            controller: logic.pwdCtrl,
            focusNode: logic.pwdFocus,
          ),
        ),
        Offstage(
          offstage: logic.isPasswordLogin.value,
          child: InputBox.verificationCode(
            label: StrRes.verificationCode,
            hintText: StrRes.plsEnterVerificationCode,
            controller: logic.verificationCodeCtrl,
            onSendVerificationCode: logic.getVerificationCode,
          ),
        ),
        30.verticalSpace,
        // Replace the existing Row with circular buttons (around line 123-147)
        // 32.verticalSpace,
      ],
    );
  }

  Widget _buildInputView2(LoginType type) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        InputBox.account(
          label: '',
          hintText: type.hintText,
          code: logic.areaCode.value,
          onAreaCode: null,
          controller: logic.phoneCtrl,
          focusNode: logic.accountFocus,
          keyBoardType: TextInputType.text,
        ),
        8.verticalSpace,
        InputBox.password(
          label: '',
          hintText: StrRes.plsEnterPassword,
          controller: logic.pwdCtrl,
          focusNode: logic.pwdFocus,
        ),
      ],
    );
  }

  void _showRegisterBottomSheet() {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: [
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                logic.operateType = LoginType.email;
                logic.registerNow();
              },
              child: Text('${StrRes.email} ${StrRes.registerNow}'),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                logic.operateType = LoginType.phone;
                logic.registerNow();
              },
              child: Text('${StrRes.phoneNumber} ${StrRes.registerNow}'),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(StrRes.cancel),
          ),
        );
      },
    );
  }

  void _showForgetPasswordBottomSheet() {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: [
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                logic.operateType = LoginType.email;
                logic.forgetPassword();
              },
              child: Text(sprintf(StrRes.through, [StrRes.email])),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                logic.operateType = LoginType.phone;
                logic.forgetPassword();
              },
              child: Text(sprintf(StrRes.through, [StrRes.phoneNumber])),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(StrRes.cancel),
          ),
        );
      },
    );
  }
 
  Widget _buildCircleButton({
  required IconData icon,
  required String label,
  required VoidCallback onTap,
}) {
  return GestureDetector(
    onTap: onTap,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 44.w,
          height: 44.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: Styles.c_8E9AB0.withOpacity(0.3),
              width: 1,
            ),
            color: Colors.white,
          ),
          child: Icon(
            icon,
            color: Styles.c_8E9AB0,
            size: 20.w,
          ),
        ),
        8.verticalSpace,
        Text(
          label,
          style: Styles.ts_8E9AB0_12sp,
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    ),
  );
}


void _showOtherLoginMethods() {
  showModalBottomSheet(
    context: Get.context!,
    backgroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
    ),
    builder: (BuildContext context) {
      return Container(
        padding: EdgeInsets.all(20.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题
            Text(
              '其他方式登录',
              style: Styles.ts_0C1C33_17sp_semibold,
            ),
            24.verticalSpace,
            _buildLoginOption(
              icon: Icons.phone_android_outlined,
              title: '手机号码登录',
              onTap: () {
                Navigator.pop(context);
                logic.loginType.value = LoginType.phone;
                logic.operateType = LoginType.phone;
              },
            ),
            // Paxly ID/邮箱登录
            _buildLoginOption(
              icon: Icons.email_outlined,
              title: '邮箱登录',
              onTap: () {
                Navigator.pop(context);
                // 处理Paxly ID/邮箱登录
                logic.loginType.value = LoginType.email;
                logic.operateType = LoginType.email;
              },
            ),
            
            // 911UBER
            _buildLoginOption(
              icon: Icons.local_taxi_outlined,
              title: '911UBER',
              onTap: () {
                Navigator.pop(context);
                // 处理911UBER登录
              },
            ),
            
            // Google登录
            _buildLoginOption(
              icon: Icons.g_mobiledata,
              title: 'Google',
              onTap: () {
                Navigator.pop(context);
                // 处理Google登录
              },
            ),
            
            20.verticalSpace,
            // 底部指示器
            Container(
              width: 134.w,
              height: 5.h,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(2.5.r),
              ),
            ),
            10.verticalSpace,
          ],
        ),
      );
    },
  );
}

// 添加登录选项构建方法
Widget _buildLoginOption({
  required IconData icon,
  required String title,
  required VoidCallback onTap,
}) {
  return GestureDetector(
    onTap: onTap,
    child: Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Icon(
            icon,
            size: 24.w,
            color: Colors.grey[600],
          ),
          16.horizontalSpace,
          Expanded(
            child: Text(
              title,
              style: Styles.ts_0C1C33_14sp,
            ),
          ),
          Icon(
            Icons.chevron_right,
            size: 20.w,
            color: Colors.grey[400],
          ),
        ],
      ),
    ),
  );
}

void _showMoreOptions() {
  showModalBottomSheet(
    context: Get.context!,
    backgroundColor: Colors.white,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
    ),
    builder: (BuildContext context) {
      return Container(
        padding: EdgeInsets.all(20.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 我的密码选项
            _buildMoreOption(
              icon: Icons.lock_outline,
              title: '找回密码',
              onTap: () {
                Navigator.pop(context);
                // 处理我的密码功能
                logic.forgetPassword();
              },
            ),
            
            // 问题反馈选项
            _buildMoreOption(
              icon: Icons.feedback_outlined,
              title: '问题反馈',
              onTap: () {
                Navigator.pop(context);
                // 处理问题反馈功能
                AppNavigator.startFeedback();
              },
            ),
            
            20.verticalSpace,
            // 底部指示器
            Container(
              width: 134.w,
              height: 5.h,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(2.5.r),
              ),
            ),
            10.verticalSpace,
          ],
        ),
      );
    },
  );
}

// 添加更多选项构建方法
Widget _buildMoreOption({
  required IconData icon,
  required String title,
  required VoidCallback onTap,
}) {
  return GestureDetector(
    onTap: onTap,
    child: Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Icon(
            icon,
            size: 24.w,
            color: Colors.grey[600],
          ),
          16.horizontalSpace,
          Expanded(
            child: Text(
              title,
              style: Styles.ts_0C1C33_14sp,
            ),
          ),
          Icon(
            Icons.chevron_right,
            size: 20.w,
            color: Colors.grey[400],
          ),
        ],
      ),
    ),
  );
}
}
